import React, {useState, useEffect} from 'react';
import {connect} from 'react-redux';
import {InputNumber, Form, Table, Modal, Button, Tooltip, Input, Select, message} from 'antd';

import {TableBtn} from "../publicComponents";
import {config, mUrl} from "../../../config";
import utils from "../../../utils/utils";
import PicturesWall from "../../../compoments/PictureWall";
import {get, post} from "../../../utils";
import {PlusOutlined, ReloadOutlined} from "@ant-design/icons";

const pathList = [
    {value: 1, name: '工厂页面'},
    {value: 2, name: '消息页面'},
    {value: 3, name: '帮助页面'},
    {value: 4, name: '投诉建议页面'},
];
const Page = () => {
    const [form] = Form.useForm();
    const [loading, setLoading] = useState(false); // 加载
    const [dataList, setDataList] = useState([]); // 列表
    const [visible, setVisible] = useState(false);
    const [imgVisible, setImgVisible] = useState(false);
    const [img, setImg] = useState('');
    const [detail, setDetail] = useState({});
    const columns = [
        {
            title: '序号',
            dataIndex: 'index',
            key: 'index',
            align: 'center',
            width: 90,
            render: (rext, record, index) => index + 1
        },
        {
            title: '操作',
            align: 'center',
            width: 100,
            render: (text, record, index) => {
                return (
                    <TableBtn
                        record={record}
                        onClick={handleTableBtnClick}
                        btns={[
                            {id: 1, name: '修改'},
                            {id: 2, name: '删除'},
                            {id: 3, name: record.viewpagerstate === 1 ? '停用' : '启用'},
                        ]}
                    />
                );
            }
        },
        {
            title: '状态',
            dataIndex: 'viewpagerstate',
            align: 'center',
            render: viewpagerstate => {
                const text = viewpagerstate === -1 ? '已停用' : '有效';
                const color = viewpagerstate === -1 ? 'red' : '#000';
                return <span style={{color}}>{text}</span>;
            }
        },
        {
            title: '图片',
            dataIndex: 'printurl',
            align: 'center',
            render: image => {
                return <span style={{cursor: 'pointer',color:'#0da8de'}} onClick={() => showImage(image)}>显示图片</span>;
            }
        },
        {
            title: '排序',
            dataIndex: 'sort',
            align: 'center',
        },
        {
            title: '转跳页面',
            dataIndex: 'sourcetype',
            align: 'center',
            render: sourcetype => {
                let text = '';
                const item = pathList.filter((item) => item.value === sourcetype);
                if (item.length) {
                    text = item[0].name;
                }
                return text;
            }
        },
        {
            title: '备注',
            dataIndex: 'remark',
            align: 'center',
            render: remark => {
                let text = remark || '--';
                return (
                    <Tooltip placement={'topLeft'} title={remark}>
                        {text.length > 15 ? text.substr(0, 15) + '...' : text}
                    </Tooltip>
                );
            }
        },
        {
            title: '创建人',
            dataIndex: 'createuser',
            align: 'center',
        },
        {
            title: '创建时间',
            dataIndex: 'createtime',
            align: 'center',
            render: create_time => utils.getDate(create_time)
        },
    ];

    const showImage = (url) => {
        setImg(url);
        setTimeout(() => {
            setImgVisible(true);
        }, 500);
    };

    useEffect(() => {
        findAll();
    }, []);

    const findAll = async () => {
        setLoading(true);
        const res = await get(mUrl.searchAllViewpagerstate, {});
        setLoading(false);
        if (res.state === 1) {
            setDataList(res.data);
        }
    };

    const handleTableBtnClick = (id, record) => {
        if (id === 1) { // 点击修改
            setDetail(record);
            setTimeout(() => {
                setVisible(true);
            }, 500);
        } else if (id === 2 || id === 3) { // 点击删除
            let viewpagerstate = -2;
            let text = '删除';
            if (id === 3) {
                viewpagerstate = record.viewpagerstate === 1 ? -1 : 1;
                text = record.viewpagerstate === 1 ? '停用' : '启用';
            }
            Modal.confirm({
                title: '提示',
                content: <span>是否确定将该轮播图<span style={{color: 'red'}}>{text}？</span></span>,
                onOk: async () => {
                    const {state} = await post(mUrl.updateViewpagerstate, {
                        ...record,
                        viewpagerstate
                    });
                    if (state === 1) {
                        message.success("成功");
                        findAll();
                    }
                }
            });
        }
    };

    return (
        <div style={{padding: 14, background: '#fff', minHeight: 360}}>
            <label><p>基础设置 / 轮播图管理</p></label>
            <Button
                onClick={() => {
                    setDetail({});
                    setVisible(true);
                }}
                style={{marginBottom: 5}} type={'primary'}>
                <PlusOutlined/>新增轮播图
            </Button>
            <Button
                onClick={() => findAll()}
                style={{marginBottom: 5, marginLeft: 5}} type={'primary'}>
                <ReloadOutlined />刷新
            </Button>
            <Table size="small"
                   rowKey={(record) => {
                       return record.viewpagerid;
                   }}
                   dataSource={dataList}
                   columns={columns}
                   pagination={{pageSize: 50}}
                   loading={loading}
                   bordered
                // onChange={handleTableChange}
            />
            <EditModal
                form={form}
                detail={detail}
                submit={() => {
                    setVisible(false);
                    findAll();
                }}
                visible={visible}
                setVisible={setVisible}
            />
            <Modal
                title={'图片'}
                visible={imgVisible}
                onCancel={_ => setImgVisible(false)}
                footer={null}
                style={{display:'flex',justifyContent:'center'}}
            >
                <img src={img} alt="" style={{width: '100%'}} />
            </Modal>
        </div>
    );
};

const EditModal = (props) => {
    const {visible = false, setVisible, detail = {}, form, submit} = props;
    const [fileList, setFileList] = useState([]);
    const [dataSource, setDataSource] = useState([]);
    const [select, setSelect] = useState(1);

    useEffect(() => {
        if (visible) {
            setSelect(detail.sourcetype || 1);
            fetch({}, {orgname: detail.orgname, orgid: detail.sourceid});
            if (detail.viewpagerid) {
                form.setFieldsValue({
                    sort: detail.sort,
                    sourceid: detail.sourceid,
                    sourcetype: detail.sourcetype,
                    orgcode: detail.orgcode,
                    remark: detail.remark,
                });
                const list = [];
                const setImgPush = (img, list, name) => {
                    const imgList = img.split(',');
                    imgList.forEach((item, index) => {
                        list.push({
                            uid: name + index,
                            name: name + index,
                            file_name: item,
                            status: 'done',
                            url: item,
                            file_path: item
                        });
                    });
                };
                setImgPush(detail.printurl, list, 'printurl');
                setFileList(list);
            }
        } else {
            form.resetFields();
            setFileList([]);
        }
    }, [visible]);

    const handleGetPictureWall = (file, fileList) => {
        // 获取上传的图片的相关信息
        setFileList(fileList);
    };

    const onFinish = (value) => {
        if (fileList.length) {
            value.printurl = utils.setImageUrl(fileList);
        } else {
            message.error('请选择轮播图');
            return false;
        }
        let url = mUrl.addViewpagerstate;
        let text = '添加';
        if (detail.viewpagerid) {
            text = '修改';
            url = mUrl.updateViewpagerstate;
            value.viewpagerid = detail.viewpagerid;
        }
        post(url, value).then((res) => {
            if (res.state === 1) {
                message.success(text + '成功');
                submit();
            }
        });
    };

    const fetch = (params = {}, select) => {
        let start = 1;
        if (params.startList > 1) {
            start = params.startList;
        }
        get(mUrl.searchOrganizationList, {pageNo: start, pageSize: 20, ...params}).then((res) => {
            const {list = []} = res.data;
            if (select.orgid) {
                const index = list.findIndex((item) => item.orgid === select.orgid);
                if (index !== 1) {
                    list.unshift(select);
                }
            }
            setDataSource(Object.assign([], list));
        });
    };

    const search = (value) => {
        fetch({orgname: value});
    };

    return (
        <Modal
            getContainer={false}
            title={detail.viewpagerid ? '修改轮播图' : '新增轮播图'}
            visible={visible}
            onCancel={_ => setVisible(false)}
            footer={null}
        >
            <Form form={form} onFinish={onFinish}>
                <Form.Item
                    required
                    label='图片'
                    labelCol={{span: 6}}
                >
                    <PicturesWall
                        size={1}
                        fileList={fileList}
                        multiple={false}
                        fileUpdate={handleGetPictureWall}
                    />
                </Form.Item>
                <Form.Item name={"sort"}
                           label={'排序'}
                           labelCol={{span: 6}}
                           rules={[{required: true, message: '请输入排序'}]}
                           style={{marginBottom: 15}}>
                    <InputNumber min={1} placeholder={'请输入'}/>
                </Form.Item>
                <Form.Item name={"sourcetype"}
                           label={'转跳页面'}
                           labelCol={{span: 6}}
                           rules={[{required: true, message: '请选择'}]}
                           style={{marginBottom: 15}}>
                    <Select style={{width: 150}}
                            onChange={(value) => {
                                setSelect(value);
                            }}
                            placeholder={'请选择'}>
                        {
                            pathList.map((item) => {
                                return (
                                    <Select.Option
                                        key={item.value} value={item.value}>
                                        {item.name}
                                    </Select.Option>
                                );
                            })
                        }
                    </Select>
                </Form.Item>
                {
                    select === 1 &&
                    <Form.Item name={"sourceid"}
                               label={'工厂名'}
                               labelCol={{span: 6}}
                               rules={[{required: true, message: '请输入工厂名'}]}
                               style={{marginBottom: 15}}>
                        <Select
                            filterOption={false}
                            showSearch onSearch={search}
                            style={{width: 200}} placeholder={'请选择'}>
                            {
                                dataSource.map((item) => {
                                    return (
                                        <Select.Option
                                            key={item.orgid} value={item.orgid}>
                                            {item.orgname}
                                        </Select.Option>
                                    );
                                })
                            }
                        </Select>
                    </Form.Item>
                }
                <Form.Item name={"remark"}
                           label={'备注'}
                           labelCol={{span: 6}}
                           style={{marginBottom: 15}}>
                    <Input.TextArea rows={2} placeholder={'请输入备注'}/>
                </Form.Item>
                <Form.Item style={{marginTop: 10, textAlign: 'center'}}>
                    <Button
                        htmlType="submit" type={'primary'}
                    >提交</Button>
                    <Button style={{marginLeft: 15}}
                            onClick={_ => setVisible(false)}
                    >取消</Button>
                </Form.Item>
            </Form>
        </Modal>
    );
};

export default connect()(Page);